<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      .active {
        text-decoration: line-through;
      }
    </style>
  </head>
  <body>
    <input type="text" id="ipt" />
    <ul>
      <!-- <li>
        <input type="checkbox" />
        <span></span>
        <button>删除</button>
      </li> -->
    </ul>
  </body>
</html>
<script>
  let oIpt = document.querySelector("#ipt");
  let oUl = document.querySelector("ul");

  let url = "http://localhost:3000/todos";
  function loadList() {
    let xhr = new XMLHttpRequest();
    xhr.open("GET", url);
    xhr.send();
    xhr.onload = function () {
      if (xhr.status == 200) {
        let obj = JSON.parse(xhr.responseText);
        oUl.innerHTML = obj
          .map(
            (v) => `<li>
                    <input type="checkbox" class="select">
                    <span>${v.title}</span>
                    <button class="del" data-id="${v.id}">删除</button>
                    </li>`
          )
          .reverse()
          .join("");
      }
    };
  }
  loadList();

  oIpt.onkeydown = function (e) {
    if (e.keyCode == 13) {
      let title = oIpt.value;
      let completed = false;
      let bodyObj = { title, completed };
      let xhr = new XMLHttpRequest();
      xhr.open("POST", url);
      xhr.setRequestHeader("content-type", "application/json");
      xhr.send(JSON.stringify(bodyObj));
      xhr.onload = function () {
        if (xhr.status == 201) {
          let obj = JSON.parse(xhr.responseText);
          loadList();
          oIpt.value = "";
        }
      };
    }
  };
  oUl.addEventListener("click", function (e) {
    if (e.target.className == "del") {
      let todoId = e.target.dataset.id;
      let delAPI = url + "/" + todoId;
      let xhr = new XMLHttpRequest();
      xhr.open("DELETE", delAPI);
      xhr.setRequestHeader("content-type", "application/json");
      xhr.send();
      xhr.onload = function () {
        if (xhr.status == 200) {
          let obj = JSON.parse(xhr.responseText);
          loadList();
        }
      };
    }
  });
  oUl.addEventListener("click", function (e) {
    if (e.target.className == "select") {
      let todoId = e.target.dataset.id;
      if (e.target.checked) {
        e.target.parentNode.classList.add("active");
      } else {
        e.target.parentNode.classList.remove("active");
      }
    }
  });
</script>
